//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by 陈伟 on 15/10/18.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import Foundation

class UserAccountViewModel {
    
    //单例的视图模型
    static let sharedUserAccount = UserAccountViewModel()
    
    //用户账户信息
    var userAccount: UserAccount?
    
    //accessToken计算型属性
//    var cwAccessToken: String? {
//        if !isExpired {
//            return userAccount?.access_token
//        }
//        return nil
//    }
    //用户登录标记
    var userLogin: Bool {
        return userAccount?.access_token != nil && !isExpired
    }
    
    private var accountPath: String {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true).last!
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    //判断是否过期
    private var isExpired: Bool {
        //如果过期时间与当前时间进行比较， 如果为降序（过期时间大于当前时间）， 为未过期
        if userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return false
        }
        return true
    }
    
    private init() {
        
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        
        if isExpired {
                //如果过期清空解档数据
            print("过期")
            userAccount = nil
        }
//        print(userAccount)
    }
}

//OAuth相关方法
extension UserAccountViewModel {
    //获取token值

    func loadAccessToken(code: String, finished: (isSuccess: Bool)->()) {
        
        //获取token值
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            
            if error != nil {
                print("OAuth里error:" + "\(error)")
                finished(isSuccess: false)
                return
            }
            
            //获取令牌
//            print("OAuth里result:" + "\(result)")
            //拿到令牌后
            //字典转模型
            guard let dict = result as? [String: AnyObject] else {
                print("滚回去检查")
                finished(isSuccess: false)
                return
            }
            self.userAccount = UserAccount(dict: dict)
            
            //            print(account)
            finished(isSuccess: true)
            self.loadAccount(self.userAccount!, finished: finished)
            
        }

    }

    //获取用户信息相关
    private func loadAccount(account: UserAccount, finished: (isSuccess: Bool)->()) {
        NetworkTools.sharedTools.loadUserInfo(account.uid!, accessToken: account.access_token!, finished: { (result, error) -> () in
            if  result == nil {
                print(error)
                finished(isSuccess: false)
            }else {
                
                guard let dict = result as? [String: AnyObject] else {
                    print("cuowu")
                    finished(isSuccess: false)
                    return
                }
                
                self.userAccount!.avatar_large = dict["avatar_large"] as? String
                self.userAccount!.screen_name = dict["screen_name"] as? String
                NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.accountPath)
                
                print(self.userAccount)
            }
        })
    }
}
